package pl.pkolodziej.platform.service.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.pkolodziej.platform.dao.user.AuthorityDAO;
import pl.pkolodziej.platform.dao.user.UserDAO;
import pl.pkolodziej.platform.vo.user.Authority;
import pl.pkolodziej.platform.vo.user.User;
import pl.pkolodziej.platform.vo.user.UserInfo;
import pl.pkolodziej.utils.StringEncrypter;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	public UserDAO userDAO;
	
	@Autowired
	public AuthorityDAO authorityDAO;
	
	@Transactional
	public void addUser(User user, Authority authority) {
		userDAO.addUser(user);
		authorityDAO.addAuthority(authority);
	}
	
	@Transactional
	public void updateUser(User user) {
		userDAO.updatedUser(user);
	}

	@Transactional(readOnly=true)
	public List<User> listUsers() {
		return userDAO.listUsers();
	}

	@Transactional
	public void removeUser(Integer id) {
		userDAO.removeUser(id);
	}
	
	public String createKey(User u){
		try{
			StringEncrypter se = new StringEncrypter(StringEncrypter.DES_ENCRYPTION_SCHEME);
			return se.encrypt(u.getUsername() + "|" + u.getPassword());
		}catch(Exception e){
			return "";
		}
	}
	
	@Transactional
	public User verifyUser(String key2){
		User u = new User();
		String key;
		try{
			StringEncrypter se = new StringEncrypter(StringEncrypter.DES_ENCRYPTION_SCHEME);
			key = se.decrypt(key2);
		}catch(Exception e){
			key = "";
		}
		System.out.print(key);
		String[] str = key.split("\\|");
		System.out.println(str.length);
		u.setUsername(str[0]);
		u.setPassword(str[1]);
		u.setEnabled(true);
		updateUser(u);
		return u;
	}
	
	@Transactional(readOnly=true)
	public User getUserPassword(String username){
		return userDAO.getUserPassword(username);
	}
	
	@Transactional(readOnly=true)
	public UserInfo getUserInfo(User user){
		return userDAO.getUserInfo(user);
	}
	
	@Transactional(readOnly=true)
	public List<UserInfo> getUsersInfo(){
		List<UserInfo> list = new ArrayList<UserInfo>();
		for (User u : listUsers() ){
			list.add(getUserInfo(u));
		}
		
		return list;
	}
	
	@Transactional
	public void updateUserInfo(UserInfo ui) {
		userDAO.updateUserInfo(ui);
	}
}
